package com.linyu.mallchat.common.user.service.impl;

import com.linyu.mallchat.common.common.constant.RedisKey;
import com.linyu.mallchat.common.common.utils.JwtUtils;
import com.linyu.mallchat.common.user.config.ThreadPoolConfig;
import com.linyu.mallchat.common.user.service.LoginService;
import com.linyu.mallchat.utils.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    public static final int TOKEN_EXPIRE_DAYS = 3;
    public static final int TOKEN_RENEWAL_DAYS = 1;
    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    @Qualifier(ThreadPoolConfig.MALLCHAT_EXECUTOR)
    private ThreadPoolExecutor threadPoolTaskExecutor;


    /**
     * 刷新token有效期
     */
    @Override
    public void renewalTokenIfNecessary(String token) {
        threadPoolTaskExecutor.execute(() ->{
            Long uid = getValidUid(token);
            String userTokenKey = getUserTokenKey(uid);
            Long expireDays = RedisUtils.getExpire(userTokenKey, TimeUnit.DAYS);
            if (expireDays == -2){ // 不存在的key
                return;
            }
            if (expireDays < TOKEN_RENEWAL_DAYS){
                RedisUtils.set(getUserTokenKey(uid), token, TOKEN_EXPIRE_DAYS, TimeUnit.DAYS);
            }
        });
    }

    /**
     * 登录返回 token
     */
    @Override
    public String login(Long uid) {
        String token =  jwtUtils.createToken(uid);
        RedisUtils.set(getUserTokenKey(uid), token, TOKEN_EXPIRE_DAYS, TimeUnit.DAYS);
        return token;
    }

    /**
     * 如果token有效，返回uid
     */
    @Override
    public Long getValidUid(String token) {
        // 拿到 token 解析，再拼接
        Long uid = jwtUtils.getUidOrNull(token);
        if (Objects.isNull(uid)){
            return null;
        }
        String oldToken = RedisUtils.get(getUserTokenKey(uid));
        if (StringUtils.isBlank(oldToken)){
            return null;
        }
        return Objects.equals( oldToken, token)? uid:null;
    }

    private String getUserTokenKey(Long uid) {
        return RedisKey.getKey(RedisKey.USER_TOKEN_STRING, uid);
    }

}
